<?php

namespace App\Install\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

class IndexController extends Controller
{

    public function checkEnv()
    {
        // 检查是否已经安装
        $installLockPath = public_path('install.lock');
        if (file_exists($installLockPath)){
            die('您已经安装过了，无需再安装！');
        }

        $problems = collect();
        $defaultPhpVersion = '7.3.0';
        $phpversion = version_compare(PHP_VERSION, $defaultPhpVersion, '>=');
        if (!$phpversion) {
            $problems->push(['message' => 'PHP 版本必须大于'.$defaultPhpVersion]);
        }

        $extension = collect([
            'dom',
            'mysqli',
            'gd',
            'json',
            'mbstring',
            'openssl',
            'pdo_mysql',
            'fileinfo'
        ])->reject(function ($extension) {
            return extension_loaded($extension);
        })->map(function ($extension) {
            return [
                'message' => "PHP扩展 '$extension' 未安装.",
            ];
        });

        $problems = $problems->merge($extension);

        $storageDirWritable = is_writable(base_path('storage'));
        $cacheDirWritable = is_writable(storage_path('cache'));
        $configDirWritable = is_writable(config_path());

        if (!$storageDirWritable) {
            $problems->push(['message' => 'storage 目录不可写']);
        }

        if (!$cacheDirWritable) {
            $problems->push(['message' => 'storage/cache 目录不可写']);
        }

        if (!$configDirWritable) {
            $problems->push(['message' => 'config 目录不可写']);
        }


        if(count($problems)>0){
            return view('install/checkenv',compact('problems'));
        }else{
            return redirect('/install/information');
        }

    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application|\Illuminate\View\View|\Laravel\Lumen\Application|\think\response\View
     */
    public function index(Request $request)
    {


        // 判断是否已经安装
        $installLockPath = public_path('install.lock');
        if (file_exists($installLockPath)){
            die('您已经安装过了，无需再安装！');
        }

        return view('install/index');
    }

    /**
     * 检查资料是否合格
     */
    public function checkInformation(Request $request)
    {
        $installLockPath = public_path('install.lock');
        if (file_exists($installLockPath)){
            die('您已经安装过了，无需再安装！');
        }

        // 返回数据
        $result = [
          'msg'=>'数据验证成功',
          'status'=>true
        ];
        // 授权检测
        $authcode = Arr::get($request, 'DENGJE_AUTHCODE');
        $query = @file_get_contents('https://auth.supengjun.com/check.php?url=' . $_SERVER['HTTP_HOST'] . '&authcode=' . $authcode);
        if ($query = json_decode($query, true)) {
            if ($query['code'] != 1) {
                return [
                    'msg'=>'授权码不正确',
                    'status'=>false
                ];
            }
        }

        // 判断两次密码
        $username =  Arr::get($request, 'adminUsername');
        $passowrd =  Arr::get($request, 'adminPassword');
        $passowrdConfirmation =  Arr::get($request, 'adminPasswordConfirmation');
        if($passowrd != $passowrdConfirmation){
            return [
                'msg'=>'两次输入的密码不相同',
                'status'=>false
            ];
        }

        if(empty($passowrd) || empty($username)){
            return [
                'msg'=>'用户名或密码不能为空',
                'status'=>false
            ];
        }

        // 缓存用户名和密码
        session(['dengje_username'=>$username]);
        session(['dengje_password'=>$passowrd]);

        // 连接数据库
        $conn = @mysqli_connect(Arr::get($request, 'DENGJE_DB_HOST'), Arr::get($request, 'DENGJE_DB_USERNAME'), Arr::get($request, 'DENGJE_DB_PASSWORD'));
        // 检测连接
        if (!$conn) {
            return [
                'msg'=>'数据库连接失败：'.mysqli_connect_error(),
                'status'=>false
            ];
        }else{
            // 写入配置env
            $configFile = file_get_contents(base_path('.env.default'));
            $repStr = str_replace([
                'DENGJE_AUTHCODE',
                'DENGJE_DB_HOST',
                'DENGJE_DB_DATABASE',
                'DENGJE_DB_USERNAME',
                'DENGJE_DB_PASSWORD'
            ], [
                Arr::get($request, 'DENGJE_AUTHCODE'),
                Arr::get($request, 'DENGJE_DB_HOST'),
                Arr::get($request, 'DENGJE_DB_DATABASE'),
                Arr::get($request, 'DENGJE_DB_USERNAME'),
                Arr::get($request, 'DENGJE_DB_PASSWORD')
            ], $configFile);
            file_put_contents(base_path('.env'),$repStr);

        }
        mysqli_close($conn);

        return $result;
    }



    /**
     * 导入sql
     * @return bool|\Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Foundation\Application|\Illuminate\View\View|\Laravel\Lumen\Application|mixed|string|\think\response\View
     */
    public function putSql()
    {
        // 判断是否已经安装
        $installLockPath = public_path('install.lock');
        if (file_exists($installLockPath)){
            die('您已经安装过了，无需再安装！');
        }

        $username = session('dengje_username');
        $password = session('dengje_password');
        $sqlPath = database_path('init.sql');
        $sqlContent = file_get_contents($sqlPath);
        $sqlContent = str_replace(['DENGJE_DEMO_USERNAME','DENGJE_DEMO_PASSWORD'],[$username,bcrypt($password)],$sqlContent);

        $database = env('DB_DATABASE');



        try{

            $db = DB::reconnect('mysql');
            $db->getPdo()->exec($sqlContent);
        }catch (\Exception $exception){
            return $exception;
        }


        file_put_contents(public_path('install.lock'),'安装锁');


        return view('install/success');
    }

}
